package info.jimao.newsdk.results;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import info.jimao.newsdk.utilities.DateDeserializer;

public class SingleDataResult<T> implements Serializable {
    private static final long serialVersionUID = 3566045462033367714L;

    private T result;
    private Class<T> type;
    private String reason;
    private Serializable error_code;

    public T getResult() {
        return result;
    }

    public void setData(T result) {
        this.result = result;
    }

    public SingleDataResult(String jsonString, Class<T> type) {
        this(jsonString, type, new DateDeserializer());
    }

    public SingleDataResult(String jsonString, Class<T> type, JsonDeserializer<Date> dateDeserializer) {
        this.type = type;
        try {
            JSONObject root = new JSONObject(jsonString);
            removeQuote(jsonString);

            Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, dateDeserializer).create();

            if (!root.isNull("result")) {
                JSONObject data = root.getJSONObject("result");
                setError_code(!root.isNull("error_code") ? root.getInt("error_code") : "");
                setReason(!root.isNull("reason") ? root.getString("reason") : "");
                setData(gson.fromJson(data.toString(), this.type));
            }

        } catch (Exception e) {
            this.reason = "数据转换异常";
            e.printStackTrace();
        }
    }

    public Serializable getError_code() {
        return error_code;
    }

    public void setError_code(Serializable error_code) {
        this.error_code = error_code;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    private String removeQuote(String jsonString){
        String regex = "\"title\":\"[^:\"]+(\"[^:\"]+\")[^\"]+\",\"date\":";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(jsonString);
        while (m.find()) {
            System.out.println(m.group());
        }

        return jsonString;
    }
}
